# -*- coding: utf-8 -*-

import odoorpc
from contextlib import contextmanager

from odoorpc import error
from odoorpc.models import MetaModel


@contextmanager
def create_odt_conn(db_name: str, ip: str, login: str, password: str, port: int):
    """
    创建odoo对象
    :param db_name: 数据库名
    :param ip: 服务端ip
    :param login: 登录名,客户端的用户名
    :param password: 登录密码，服务的密码
    :param port: 服务端口号
    :return: odoo对象
    """

    dtcloud = odoorpc.ODOO(ip, port=port)
    try:
        dtcloud.login(db_name, login=login, password=password)
        yield dtcloud
    except Exception as e:
        raise e
    finally:
        dtcloud.logout()


# 若不使用odoorpc，可以使用下面的方法
# from dtcloud.modules.registry import Registry
# from dtcloud.api import Environment, SUPERUSER_ID

# with Registry('dtcloud').cursor() as cr:
#     env = Environment(cr, SUPERUSER_ID, {})
#     print(env['res.users'].search_count([]))


if __name__ == '__main__':
    with create_odt_conn('qedtcloud', '127.0.0.1', 'admin', 'admin',9096) as request:
        basemodel = request.env['res.users']
        # print(f"\033[35m --- {type(basemodel)} ---\033[0m")
        search_domain = [('login', '=', 'admin')]
        res_id = basemodel.search(search_domain)  # 返回的是一个列表
        res_user = basemodel.browse(res_id)  # 返回的是一个对象
        # 改
        res_user.write({'name': '123'})
        # 增
        # basemodel.create({'name': '123'})
        # 删
        # res_user.unlink()

        basemodel.search_read(search_domain, ['name'])
        basemodel.search_count(search_domain)
        print(basemodel.read_group(search_domain, ['name'], ['name']))
